package com.chainyoung.component_tmmarket.adapter;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chainyoung.component_tmmarket.R;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CoupleListAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

    private String keyword;

    private View.OnClickListener onClickListener;


    public CoupleListAdapter(Context context, @Nullable List<String> data, String keyWord) {
        super(R.layout.tmmarket_list_couple_item, data);
        mContext = context;
        this.keyword = keyWord;
    }

    @Override
    protected void convert(BaseViewHolder helper, String item) {
        TextView tvName = helper.getView(R.id.tv_name);
        if (TextUtils.isEmpty(keyword)) {
            tvName.setText(item);
        } else {
            tvName.setText(matcherSearchTitle(ContextCompat.getColor(mContext, R.color._4486f5), item, keyword));
        }
        tvName.setOnClickListener(onClickListener);
        tvName.setTag(item);
    }


    private SpannableString matcherSearchTitle(int color, String text, String keyword) {
        String str = text.toLowerCase();
        String key = keyword.toLowerCase();
        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(str);
        SpannableString ss = new SpannableString(text);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }

    public void setKeyWord(String keyword){
        this.keyword=keyword;
    }

    public void setOnClickListener(View.OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }
}
